package smetana.modules.ui.form.window;

import org.apache.pivot.wtk.Action;
import org.apache.pivot.wtk.PushButton;
import org.apache.pivot.wtk.TextArea;
import org.apache.pivot.wtkx.WTKX;
import smetana.modules.ui.form.AbstractPanel;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author dmitry.mamonov
 */
public abstract class ShowExceptionPanel extends AbstractPanel {

    @WTKX
    PushButton buttonClose;
    @WTKX
    TextArea textBrief;
    @WTKX
    TextArea textDetails;

    Action actionClose = new Action() {
        @Override
        public void perform() {
            close();
        }
    };

    protected ShowExceptionPanel() {
        super(ShowExceptionPanel.class);
    }

    @Override
    protected void init() {
        wtkx.bind(this, ShowExceptionPanel.class);
        buttonClose.setAction(actionClose);
    }

    public void setThrowable(Throwable th) {
        this.getComponent(); //make sure that all components are initialized.
        if (th == null) {
            textBrief.setText("<empty>");
            textDetails.setText("<empty>");
        } else {
            //setup brief text
            StringBuilder brief = new StringBuilder();
            Throwable currentThrowable = th;
            int depth = 0;
            while (currentThrowable != null && depth < 10) {
                String message = currentThrowable.getMessage();
                if (message != null) {
                    for (String line : message.split("\n")) {
                        line = line.trim();
                        if (line.isEmpty() == false) {
                            brief.append(line).append("\n");
                        }
                    }
                }
                currentThrowable = currentThrowable.getCause();
                depth++;
            }
            if (brief.length()==0){
                brief.append(th.getClass().getName());
            }
            textBrief.setText(brief.toString());

            //setup full stack trace
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            th.printStackTrace(pw);
            pw.flush();
            textDetails.setText(sw.toString());
        }
    }

    protected abstract void close();

}
